<template>
  <div id="projectContract">
    <div class="search">
      <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
        <el-form-item label="合同名称：">
          <el-input
            v-model="searchFrom.htmc"
            placeholder="请输入合同名称"
            style="width: 380px"
          ></el-input>
        </el-form-item>
        <el-form-item label="合同乙方：">
          <el-input
            v-model="searchFrom.cydw"
            placeholder="请输入合同乙方"
            style="width: 380px"
          ></el-input>
        </el-form-item>
        <el-form-item style="margin-left: 0.7143rem">
          <el-button class="generalButton" icon="el-icon-search" @click="search"
            >查询</el-button
          >
          <el-button class="generalButton" icon="el-icon-refresh-right" @click="reset"
            >重置</el-button
          >
          <!-- <el-button class="generalButton">统计信息</el-button> -->
        </el-form-item>
      </el-form>
      <div>
        <el-button class="generalButton" icon="el-icon-plus" @click="addPlat">新增</el-button>
      </div>
    </div>
    <div class="table">
      <el-alert style="background: #e6f7ff" :closable="false">
        <span style="color: #64736c">已选择</span>
        <span style="color: #519df8">{{ selectData.length }}</span>
        <span style="padding-right: 1.3571rem; color: #64736c">项</span>
        <span style="color: #519df8; cursor: pointer" @click="clear()"
          >清空</span
        >
      </el-alert>
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        border
        :cell-style="cellStyle"
        highlight-current-row
        :header-cell-style="{
          background: '#2B69A6',
          color: '#fff',
          borderColor: '#BDE1FC',
        }"
        tooltip-effect="dark"
        style="width: 100%; margin-top: 0.8571rem"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column label="序号" type="index" width="80" align="center">
        </el-table-column>
        <el-table-column prop="htbh" label="合同编号" align="center">
        </el-table-column>
        <el-table-column prop="htmc" label="合同名称" align="center">
        </el-table-column>
        <!-- <el-table-column
                prop="endTime"
                label="项目编号" align="center"
                >
                </el-table-column> -->
        <el-table-column prop="htjf" label="合同甲方" align="center">
        </el-table-column>
        <el-table-column prop="cydw" label="合同乙方" align="center">
        </el-table-column>
        <!-- <el-table-column
                prop="note"
                label="承研单位" align="center"
                >
                </el-table-column> -->
        <el-table-column prop="kssj" label="合同开始日期" align="center">
        </el-table-column>
        <el-table-column prop="jsrq" label="合同结束日期" align="center">
        </el-table-column>
        <el-table-column prop="htje" label="合同金额(万元)" align="center">
        </el-table-column>
        <el-table-column prop="fjmc" label="附件" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.fjmc[0]}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="text" style="padding-right: 0.5rem" @click="editPlat(scope.row)"
              >编辑</el-button
            >
            <el-popover placement="bottom" trigger="click">
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                "
              >
                <el-button type="text" style="color: #000" @click="downfiles(scope.row)">下载附件</el-button>
                <el-button
                  type="text"
                  style="color: #000"
                  @click="managementBtn(scope.row)"
                  >经费管理</el-button
                >
                <el-button type="text" style="color: #000" @click="deletehetong(scope.row)">删除</el-button>
              </div>
              <el-button type="text" slot="reference"
                >更多<i class="el-icon-arrow-down el-icon--right"></i
              ></el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.currentPage"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.totalCount"
      >
      </el-pagination>
    </div>
    <!-- 经费管理  父给子传值； 子给父传值@ -->
    <dialogManager
      v-if="dialogManager"
      ref="dialogManager"
      @closejingfeiDialog="closejingfeiDialog"
    ></dialogManager>

    <!-- 新增/编辑合同 -->
    <el-dialog
      :visible.sync="addPlatDialogVisible"
      width="50%"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div slot="title" class="title">
        <div><span>{{title}}</span></div>
        <div>
          <i
            class="el-icon-close"
            @click="addPlatDialogVisible = false"
          ></i>
        </div>
      </div>
      <div class="content">
        <el-form
          ref="addplatform"
          :model="addplatform"
          label-width="150px"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item label="合同编号：" prop="htbh">
            <el-input
              v-model="addplatform.htbh"
              placeholder="请输入合同编号"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同名称：" prop="htmc">
            <el-input
              v-model="addplatform.htmc"
              placeholder="请输入合同名称"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同甲方：" prop="htjf">
            <el-input
              v-model="addplatform.htjf"
              placeholder="请输入合同甲方"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同乙方：" prop="cydw">
            <!-- <el-input
              v-model="addplatform.cydw"
              placeholder="请输入合同乙方"
              :rows="3"
            ></el-input> -->
            <el-autocomplete
              class="inline-input"
              v-model="addplatform.cydw"
              :fetch-suggestions="querySearch"
              placeholder="请输入合同乙方"
              style="width: 100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="合同开始日期：" prop="kssj">
            <el-date-picker
              v-model="addplatform.kssj"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="合同结束日期：" prop="jsrq">
            <el-date-picker
              v-model="addplatform.jsrq"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              style="width: 100%"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="合同金额(万元)：" prop="htje">
            <el-input
              v-model="addplatform.htje"
              placeholder="请输入合同金额"
              :rows="3"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="是否军方单位：">
            <el-select
              v-model="addplatform.name"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option label="是" value="0"> </el-option>
              <el-option label="否" value="1"> </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="附件：">
            <el-upload
                  class="upload-demo"
                  action=""
                  :on-preview="handlePreview"
                  multiple
                  :limit="3"
                  :file-list="fileList"
                  :http-request="httpRequest"
                  :auto-upload="false"
                  ref="upload"
                  style="display:inline-block"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <!-- <div slot="tip" class="el-upload__tip">
                    只能上传jpg/png文件，且不超过500kb
                  </div> -->
                </el-upload>
          </el-form-item>
          <!-- <el-form-item label="附件："></el-form-item> -->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="contentButton">
          <el-button @click="addPlatDialogVisible = false; $refs.addplatform.resetFields()">取消</el-button>
          <el-button @click="addhetong" class="generalButton">确定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dialogManager from "./managerDialong";
import { gethetonggl, addhetonggl, edithetonggl, searchht } from "@/api/gcxinxigl.js"
import { Uploadfujian, downfile, downfile1 } from "api/jscsdpg"
export default {
  components: {
    dialogManager,
  },
  data() {
    return {
      dialogManager: false,
      // 标题
      title: '',
      flag: '',
      fileList: [],
      // 选中表格多少跳
      selectData: [],
      // 经费管理对话框是否显示
      isDialog: false,
      // 新增合同对话框
      addPlatDialogVisible: false,
      addplatform: {
        cjr: 'admin',
        gxr: 'admin',
        xlzt: '1'
      },
      loading: false,
      // 合同新增验证规则 
      rules: {
        htbh: [
          // { required: true, message: '请输入合同编号', trigger: 'blur' },
          { max: 20, message: '合同编号录入不可超过20字', trigger: 'blur' }
        ],
        htmc: [
          { required: true, message: '请输入合同名称', trigger: 'blur' },
          { max: 50, message: '合同名称录入不可超过50字', trigger: 'blur' }
        ],
        htjf: [
          { required: true, message: '请输入合同甲方', trigger: 'blur' },
          { max: 50, message: '合同甲方录入不可超过50字', trigger: 'blur' }
        ],
        cydw: [
          { required: true, message: '请输入合同乙方', trigger: 'change' },
          { max: 50, message: '合同乙方录入不可超过50字', trigger: 'blur' }
        ],
        kssj: [
          { required: true, message: '请输入合同开始日期', trigger: 'blur' }
        ],
        jsrq: [
          { required: true, message: '请输入合同结束日期', trigger: 'blur' }
        ],
        htje: [
          { required: true, message: '请输入合同金额', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '仅可录入正整数', trigger: 'blur'}
        ],
      },
      // 分页
      pageInfo: {
        currentPage: 1,
        totalCount: 0,
        pageSize: 0,
      },
      // 表单
      searchFrom: {
       
      },
      // 表格
      tableData: [
       
      ],
      // 搜索建议列表
      restaurants: [],
      id: ''
    }
  },
  mounted () {
    this.init()
    this.restaurants = this.loadAll()
  },
  methods: {
    init() {
      this.loading = true
      gethetonggl(this.pageInfo).then(res => {
        console.log(res)
        this.tableData = res.data
        this.pageInfo = res.pageInfo
        this.loading = false
      }).catch(err => {
        console.log(err);
      })
    },
    // 新增合同
    addPlat() {
      this.addPlatDialogVisible = true
      this.title = '新增合同'
      this.flag = '0'
    },
    // 编辑合同
    editPlat(data) {
      this.addPlatDialogVisible = true
      this.title = '编辑合同'
      this.flag = '1'
      this.addplatform = data
    },
    // 上传附件
    httpRequest(param) {
      let fileObj = param.file; // 相当于input里取得的files
      let fd = new FormData(); // FormData 对象
      fd.append("file", fileObj); // 文件对象
      Uploadfujian(this.id,'0',fd).then(res=>{
        console.log(res);
      })
    },
    // 新增合同接口
    addhetong() {
      console.log(this.flag, '******');
      this.$refs['addplatform'].validate((value) => {
        if (value) {
          // 添加合同
          if (this.flag === '0') {
            addhetonggl(this.addplatform).then(res => {
              console.log(res, '新增成功');
              this.id = res.data.id
              this.$refs.upload.submit()
              // debugger
              this.$message.success('添加成功！')
              this.addPlatDialogVisible = false
              this.$refs.addplatform.resetFields()
              this.init()
            }).catch(err => {
              console.log(err)
            })
          } else if (this.flag === '1') {
          // 编辑合同
            edithetonggl(this.addplatform.id, this.addplatform).then(res => {
              // console.log(res, '编辑成功')
              this.$message.success('编辑成功！')
              this.addPlatDialogVisible = false
              this.init()
            }).catch(err => {
              console.log(err)
            })
          }
        }
      })
    },
    // 删除合同
    deletehetong(data) {
      edithetonggl(data.id, {xlzt: '0'}).then(res => {
        this.$message.success('删除成功！')
        this.init()
      }).catch(err => {
        console.log(err)
      })
    },
    // 下载附件
    downfiles(data) {
      // debugger
      downfile1(data.id, 0).then(res => {
        console.log(res, '++++++')
        // 下载压缩包文件
        if (res.data === '2') {
          downfile(data.id, 0).then(res => {
          let blob = new Blob([res], {
          type: "application/zip"
          });
          const link = document.createElement("a");
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.setAttribute("download", '压缩包.zip');
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);

          // const url = window.URL.createObjectURL(blob)
          // window.location.href = url
          })
        } else if (res.data === '1') {
          // 下载单个文件
            downfile(data.id, 0).then(res => {
              console.log(res, '+++');
              let blob = new Blob([res], {
              type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8",
            });
            const link = document.createElement("a");
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            link.setAttribute("download", data.fjmc);
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
          })
        }
      }).catch(err => {
        console.log(err)
      })
      
    },
    // 查询
    search() {
      searchht(this.searchFrom).then(res => {
        console.log(res, '[[[[');
        this.tableData = res.data
        this.pageInfo = res.pageInfo
      }).catch(err => {
        console.log(err)
      })
    },
    reset() {
      this.searchFrom = {}
    },
    // 清除选中项
    clear() {
      (this.selectData = []), this.$refs.multipleTable.clearSelection();
    },
    // 是否关闭经费管理
    closejingfeiDialog() {
      this.dialogManager = false
    },
    // 经费管理
    managementBtn(value) {
      this.dialogManager = true
      this.$nextTick(() => {
        this.$refs.dialogManager.init(value)
      })
    },
    handleSelectionChange(val) {
      this.selectData = val;
    },
    // 更改边框颜色
    cellStyle() {
      return "border-color:#BDE1FC;";
    },
    // 页数总数改变
    handleSizeChange(val) {
      this.pageInfo.pageSize = val
      this.init()
    },
    // 当前页数改变
    handleCurrentChange(val) {
      this.pageInfo.currentPage = val
      this.init()
    },
    handlePreview(file) {
      console.log(file)
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().match(queryString.toLowerCase()))
      }
    },
    loadAll() {
      return [
        { "value": "一院" },
        { "value": "一飞院" },
        { "value": "空8所" },
        { "value": "十二院" }
      ]
    }
  }
}
</script>

<style lang="less" scoped>
#projectContract {
  background: #fff;
  color: #000;
  padding: 1.4286rem;
}
.search {
  padding-bottom: 0.9286rem;
}
.title {
  color: #000;
  background: #fff;
  font-size: 1.1429rem;
  height: 3.5714rem;
  display: flex;
  align-items: center;
  padding: 0 1.4286rem;
  border-bottom: 1px solid #eeeeee;
  justify-content: space-between;
}
.demo-form-inline {
  width: 100%;
}
.el-table td,
.el-table th.is-leaf,
.el-table--border,
.el-table--group {
  border-color: #bde1fc;
}
.el-table--border::after,
.el-table--group::after,
.el-table::before {
  background-color: #bde1fc;
}
.pagination {
  padding-top: 0.7143rem;
  display: flex;
  align-items: flex-end;
  justify-content: flex-end;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 3.5rem;
  background: #fff;
  border-top: 1px solid #eeeeee;
}
</style>